package com.ponxu.web.core;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ponxu.config.Properties;
import com.ponxu.utils.Lang;

import freemarker.ext.servlet.AllHttpScopesHashModel;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * Freemarker处理
 * 
 * @author xwz
 * 
 */
public class FreeMarkerResultRender extends ResultRender {
	private Configuration cfg;
	private ObjectWrapper wrapper;
	private ServletContext servletContext;

	public void init(ServletContext app) {
		try {
			servletContext = app;
			cfg = new Configuration();
			Properties props = new Properties();

			InputStream in = FreeMarkerResultRender.class
					.getResourceAsStream("/freemarker.properties");
			props.load(in);

			cfg.setServletContextForTemplateLoading(servletContext,
					props.getProperty("TEMPLATE_DIR"));
			cfg.setTemplateUpdateDelay(Integer.parseInt(props
					.getProperty("UPDATE_DELAY")));
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);

			wrapper = createObjectWrapper();
			cfg.setObjectWrapper(wrapper);

			cfg.setDefaultEncoding(props.getProperty("DEFAULT_ENCODING"));
			cfg.setOutputEncoding(props.getProperty("OUTPUT_ENCODING"));

			in.close();
			in = null;
			props = null;
		} catch (IOException e) {
			Lang.makeThrow(e);
		}
	}

	private ObjectWrapper createObjectWrapper() {
		return ObjectWrapper.BEANS_WRAPPER;
	}

	public void render(HttpServletRequest request,
			HttpServletResponse response, String result)
			throws ServletException, IOException {
		if (Lang.isEmpty(result))
			return;
		Template t = cfg.getTemplate(result);
		AllHttpScopesHashModel params = new AllHttpScopesHashModel(wrapper,
				servletContext, request);
		try {
			t.process(params, response.getWriter());
		} catch (TemplateException e) {
			Lang.makeThrow(e);
		}
	}
}
